//导入数据关联
//导入express模块和MySQL模块
var mysql = require('mysql');
var express = require("express");
//执行experss
var app = express();

//使用bodyParser模块，接收post参数
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


//设置跨域访问（设置在所有的请求前面即可）
app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method == 'OPTIONS')
        res.send(200); //让options尝试请求快速结束
    else
        next();
});


app.get("/", function (req, res) {
    console.log(req.query)
    //传送HTTP响应
    res.send("hello ,欢迎访问后端")
})


// app.get("/queryAllUsers", function (req, res) {
//     // console.log("开始查询所有用户信息")
//     //直接去数据库查询所有的数据
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: '123456',
//         port: '3306',
//         database: 'vue'
//     });
//     connection.connect();
//     //sql语句
//     var sql = `select * from users`;
//     //执行sql
//     connection.query(sql, function (error, result) {
//         if (error) {
//             console.log("出错了：" + error.message);
//             res.send({
//                 state: false,
//                 des: "出错了：" + error.message
//             })
//         }
//         else {
//             if (result.length == 0) {
//                 res.send({
//                     state: true,
//                     des: "无任何用户数据！"
//                 })
//             }
//             else {
//                 res.send({
//                     state: true,
//                     des: result
//                 })
//             }
//         }
//         //关闭数据库连接
//         connection.end();
//     })
// })


app.get("/queryAll", function (req, res) {
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'shang'
    });
    connection.connect();
    //sql语句
    var sql = `select * from page`;
    //执行sql
    connection.query(sql, function (error, result) {
        if (error) {
            console.log("出错了：" + error.message);
            res.send({
                state: false,
                des: "出错了：" + error.message
            })
        }
        else {
            if (result.length == 0) {
                res.send("无任何用户数据！")
            }
            else {
                res.send(result)
            }
        }
        //关闭数据库连接
        connection.end();
    })
})

app.post("/queryID", function (req, res) {
    //req.body / req.cookies：获得「请求主体」/ Cookies
    console.log(req.body.id);
    //console.log(req.body.age);
    //console.log(req.query.name) req.query：获取URL的查询参数串
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'shang'
    });
    connection.connect();
    var sql = `select * from xiangqing where id=?`;
    connection.query(sql, [req.body.id], function (error, result) {
        console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }

        if (result.length > 0) {
            res.send(result)
        }
        else {
            res.send('商品详情获取失败')
        }
        connection.end()
    })
})

app.post("/queryUser", function (req, res) {
    //req.body / req.cookies：获得「请求主体」/ Cookies
    console.log(req.body.name);
    //console.log(req.body.age);
    //console.log(req.query.name) req.query：获取URL的查询参数串
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'shang'
    });
    connection.connect();
    var sql = `select * from user where username=?`;
    connection.query(sql, [req.body.user], function (error, result) {
        console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }

        if (result.length > 0) {
            console.log(result[0].password == req.body.password);
            if (result[0].password == req.body.password) {
                res.send('登录成功')
            } else {
                res.send("密码错误")
            }
        }
        else {
            res.send('用户名错误')
        }
        connection.end()
    })
})

app.post("/addUser", function (req, res) {
    //req.body / req.cookies：获得「请求主体」/ Cookies
    // console.log(req.body.name);
    //console.log(req.body.age);
    //console.log(req.query.name) req.query：获取URL的查询参数串
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'shang'
    });
    connection.connect();

    var sql = `select * from user where username=?`;
    connection.query(sql, [req.body.name], function (error, result) {
        // console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }

        if (result.length > 0) {
            res.send("用户已经存在");
        }
        else {
            sql = 'INSERT INTO `user` ( `username`, `password`) VALUES ( ?, ?)';
            connection.query(sql, [req.body.name, req.body.password], function (error, result) {
                console.log(result)
                if (error) {
                    console.log("出错了", error.message);
                    res.send("出错了：" + error.message)
                    con.end()
                    return;
                }
                res.send('注册成功')
                connection.end()
            })
        }
        connection.end()
    })
})

app.post("/queryLogin", function (req, res) {
    //req.body / req.cookies：获得「请求主体」/ Cookies
    console.log(req.body.name);
    //console.log(req.body.age);
    //console.log(req.query.name) req.query：获取URL的查询参数串
    // console.log("开始查询所有用户信息")
    //直接去数据库查询所有的数据
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '123456',
        port: '3306',
        database: 'shang'
    });
    connection.connect();
    var sql = `select * from users where id=?`;
    connection.query(sql, [req.body.name], function (error, result) {
        console.log(result)
        if (error) {
            console.log("出错了", error.message);
            res.send("出错了：" + error.message)
            con.end()
            return;
        }

        if (result.length > 0) {
            res.send(result)
        }
        else {
            res.send({
                mes: '登录失败',
                data: result
            })
        }
        connection.end()
    })
})

app.listen(8081, function () {
    console.log("后端监听的地址为：http://127.0.0.1:8081")
})